﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RestaurantApp.Web.Infrastructure.Poco
{
    public static class ControllerExtensions
    {
        public static T CreateInstance<T>(this Controller sender) where T : class
        {
            T obj = (T)Activator.CreateInstance<T>();
            foreach (var info in obj.GetType().GetProperties())
            {
                if (info.PropertyType.IsClass && info.PropertyType.ToString().Contains("TimeBase"))
                {
                    try
                    {
                        object innerobj = Activator.CreateInstance(info.PropertyType);
                        info.SetValue(obj, innerobj, null);
                    }
                    catch
                    {
                    }
                }
            }
            return obj;            
        }

        public static void CreateInstance(this Controller sender,object obj)
        {
            foreach (var info in obj.GetType().GetProperties())
            {
                if (info.PropertyType.IsClass && info.PropertyType.ToString().Contains("TimeBase"))
                {
                    try
                    {
                        try
                        {
                            object value = info.GetValue(obj, null);
                            if (value == null)
                            {
                                object innerobj = Activator.CreateInstance(info.PropertyType);
                                info.SetValue(obj, innerobj, null);
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }

    }
}